/*
 * @Author: your name
 * @Date: 2020-03-20 14:17:34
 * @LastEditTime: 2020-03-26 11:27:50
 * @LastEditors: your name
 * @Description: In User Settings Edit
 * @FilePath: 。。。。。。。。。。
 */
import axios from 'axios'
import baseUrl from '@/config/index'
import { getLocal, remove } from '@/utils/storage.ts'
import store from '@/store'

// create an axios instance
const service = axios.create({
  baseURL: baseUrl,
  timeout: 80000 // request timeout
})

// //请求拦截
service.interceptors.request.use(
  config => {
    const token = store.state.token
    if (token) {
      // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
      config.headers.Authorization = 'Bearer ' + token
      // config.headers['Content-Type']='application/x-www-form-urlencoded'

    }
    return config
  },
  error => {
    // Do something with request error
    $message.error(error)
    Promise.reject(error)
  }
)
service.interceptors.response.use((response) => {
  const { code, data, msg } = response.data
  if (response.status === 200) {
    if (code === 200) {
      return data
    }else{
      Promise.reject('错误')
    }
    switch(code){
      case 50001:
        window.$message.error('登录过期！')
        window.location.href="/login"
        remove('token')
        store.dispatch('setMyToken', '')
        break;
    }

  } else {
    // 其他网络错误
    $message.error('网络错误')
  }
  // 处理响应数据
  return response
}, (error) => {
  console.log('======',error)
  switch (error.response?.status) {
    case 500:
      $message.error('请联系管理员')
      break;
  }

  // 处理响应失败
  return Promise.reject(error)
})


export default service